<?php

declare(strict_types=1);

namespace app\middleware;

use think\facade\Cache;

function setLog($count, $key)
{
    $file_name = $_SERVER['DOCUMENT_ROOT'] . "/../api_resource/logs/" . date('Ymd') . "_ip_black.log";

    file_put_contents($file_name, date('Y-m-d H:i:s') . "--------请求次数:" . $count . "---------", FILE_APPEND);
    file_put_contents($file_name, "\r\n", FILE_APPEND);
    file_put_contents($file_name, "redis=>key:" . $key, FILE_APPEND);
    file_put_contents($file_name, "\r\n", FILE_APPEND);
}

class RequestLimit
{
    protected $limit_count = 3; //提交了次数限制
    protected $expire_time = 1; //单位s
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        //
        $ip = $request->ip();
        // $limit_ip = Cache::get('ip_' . $ip);
        // if ($limit_ip) {
        //     return error('ip限制访问');
        // }
        if ($request->method() == 'POST') {
            $this->limit_count = 1;
        }
        if ($request->method() == 'GET') {
            $this->limit_count = 4;  //get请求默认3次
        }
        $user = null;
        if ($request->officialUser) {
            $user = $request->officialUser;
        } else if ($request->authInfo) {
            $user = $request->authInfo;
        }

        $user_id = 0; //用户id默认为0
        $user_type = "";
        if ($user) {
            $user_id = $user['user_id'];
            $user_type = $user['user_type'];
        } else {
            // 限制请求中间件处理之前未对用户登录做验证或者不需要登录用户做验证
            // storage_log('限制请求中间件处理之前未对用户登录做验证,当前访问ip:' . $ip);
        }

        $index = input('index');
        $request_route_rule = $request->rule()->getRule();
        $perm = str_replace('/', ':', $request_route_rule);

        $key = 'request_info_' . $user_type . "_" . $user_id . "_" . $ip . "_" . $request_route_rule;
        // storage_log("setKey:" . $key);

        if (Cache::get($key)) {
            // 重复请求
            Cache::inc($key);  //自增1
            $count  = Cache::get($key);
            // if ($count > $this->limit_count) {
            //     // todo 是否添加到ip黑名单 提交上限
            //     // Cache::set('ip_' . $ip, $ip, 10);
            // }
            if ($count > $this->limit_count) {
                setLog($count, $key);
                return error('处理中,请稍候...', 500);
            }
        } else {
            // 设置1秒
            Cache::set($key, 1, $this->expire_time);
        }
        return $next($request);
    }
}
